package com.softlab.logsystem.service.rabbitmq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.softlab.logsystem.common.util.JsonUtil;
import com.softlab.logsystem.core.model.LogDto;
import com.softlab.logsystem.service.ConsumerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author LiXiwen
 * @date 2020/1/7 14:45
 */
@Component
public class ConsumerListener implements ChannelAwareMessageListener {
    private static final Logger logger = LoggerFactory.getLogger(ConsumerListener.class);

    private final ObjectMapper objectMapper;
    private final ConsumerService consumeService;

    @Autowired
    public ConsumerListener(ObjectMapper objectMapper, ConsumerService consumeService) {
        this.objectMapper = objectMapper;
        this.consumeService = consumeService;
    }

    /**
     * 监听消息队列，接收对象消息
     * @param message
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long tag=message.getMessageProperties().getDeliveryTag();
        try {
            byte[] msg=message.getBody();
            LogDto logDto = objectMapper.readValue(msg, LogDto.class);
            logger.info("接收到对象消息 : logDto = " + JsonUtil.getJsonString(logDto));
            consumeService.addlogDto(logDto);
            //int i=1/0;
            channel.basicAck(tag,true);
        } catch (Exception e) {
            logger.error("监听消费消息 发生异常： ", e.fillInStackTrace());
            channel.basicReject(tag,false);
        }
    }


}
